package org.jeecg.modules.online.cgform.util;

import cn.hutool.core.io.FileUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtil {

    public static File compressFiles(List<String> files, String path) throws RuntimeException {
        File zipFile = FileUtil.touch(path);
        if (zipFile == null) {
            return null;
        } else if (!zipFile.getName().endsWith(".zip")) {
            return null;
        } else {
            ZipOutputStream stream = null;

            try {
                FileOutputStream fileStream = new FileOutputStream(zipFile);
                stream = new ZipOutputStream(fileStream);
                Iterator<String> iterator = files.iterator();

                while(true) {
                    File file;
                    do {
                        do {
                            if (!iterator.hasNext()) {
                                if (stream != null) {
                                    try {
                                    	stream.close();
                                    } catch (IOException e) {
                                        System.out.println("ZipUtil toZip close exception" + e);
                                    }
                                }

                                fileStream.close();
                                return zipFile;
                            }

                            String fileName = iterator.next();
                            fileName = URLDecoder.decode(fileName, "UTF-8").replace("生成成功：", "");
                            file = new File(fileName);
                        } while(file == null);
                    } while(!file.exists());

                    byte[] line = new byte[4096];
                    String filePath = null;
                    if (file.getAbsolutePath().indexOf("src\\") != -1) {
                    	filePath = file.getAbsolutePath().substring(file.getAbsolutePath().indexOf("src\\") - 1);
                    } else {
                    	filePath = file.getAbsolutePath().substring(file.getAbsolutePath().indexOf("src/") - 1);
                    }

                    stream.putNextEntry(new ZipEntry(filePath));
                    FileInputStream input = new FileInputStream(file);

                    int i;
                    while((i = input.read(line)) != -1) {
                    	stream.write(line, 0, i);
                    }

                    input.close();
                    stream.closeEntry();
                }
            } catch (Exception e) {
                throw new RuntimeException("zipFile error from ZipUtils", e);
            }
        }
    }
}
